package com.muyu.system.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.system.Vo.FindCartVO;
import com.muyu.system.domain.*;
import com.muyu.system.dto.FindCartDTO;
import com.muyu.system.mapper.*;
import com.muyu.system.req.CartItemDto;
import com.muyu.system.req.ShoppingCartDto;
import com.muyu.system.req.ShoppingCartModificationDto;
import com.muyu.system.service.IDanmoShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车Service业务层处理
 *
 * @author yangle
 * @date 2024-09-29
 */
@Service
public class DanmoShoppingCartServiceImpl implements IDanmoShoppingCartService {
    @Autowired
    private DanmoShoppingCartMapper danmoShoppingCartMapper;

    @Autowired
    private DanmoShoppingProductsMapper danmoShoppingProductsMapper;

    @Autowired
    private DanmoShoppingFootprintMapper danmoShoppingFootprintMapper;

    @Autowired
    private DanmoShoppingFlagshipMapper danmoShoppingFlagshipMapper;

    @Autowired
    private DanmoShoppingSpecificationMapper danmoShoppingSpecificationMapper;

    @Autowired
    private DanmoShoppingProductsCollectionMapper danmoShoppingProductsCollectionMapper;

    @Autowired
    private DmShoppingCartMapper dmShoppingCartMapper;

    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public DanmoShoppingProducts selectDanmoShoppingCartById(Long id) {
        DanmoShoppingCart danmoShoppingCart = danmoShoppingCartMapper.selectDanmoShoppingCartById(id);
        DanmoShoppingFootprint danmoShoppingFootprint = new DanmoShoppingFootprint();
        danmoShoppingFootprint.setUserId(danmoShoppingCart.getUserId());
        danmoShoppingFootprint.setProductId(danmoShoppingCart.getProductId());
        danmoShoppingFootprint.setCreateBy(danmoShoppingCart.getCreateBy());
        danmoShoppingFootprint.setCreateTime(danmoShoppingCart.getCreateTime());
        danmoShoppingFootprint.setUpdateBy(danmoShoppingCart.getUpdateBy());
        danmoShoppingFootprint.setUpdateTime(danmoShoppingCart.getUpdateTime());
        danmoShoppingFootprintMapper.insertDanmoShoppingFootprint(danmoShoppingFootprint);
        return danmoShoppingProductsMapper.getById(danmoShoppingCart.getProductId());
    }

    /**
     * 查询购物车列表
     *
     * @param danmoShoppingCart 购物车
     * @return 购物车
     */
/*    @Override
    public List<DanmoShoppingCart> selectDanmoShoppingCartList(DanmoShoppingCart danmoShoppingCart)
    {
        return danmoShoppingCartMapper.selectDanmoShoppingCartList(danmoShoppingCart);
    }*/

    /**
     * 新增购物车
     *
     * @param danmoShoppingCart 购物车
     * @return 结果
     */
    @Override
    public int insertDanmoShoppingCart(DanmoShoppingCart danmoShoppingCart) {
        danmoShoppingCart.setCreateTime(DateUtils.getNowDate());
        return danmoShoppingCartMapper.insertDanmoShoppingCart(danmoShoppingCart);
    }

    /**
     * 修改购物车
     *
     * @param shoppingCartModificationDto 购物车
     * @return 结果
     */
    @Override
    public Result updateDanmoShoppingCart(ShoppingCartModificationDto shoppingCartModificationDto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserid();
        if (shoppingCartModificationDto.getId() != null) {
            DanmoShoppingCart danmoShoppingCart = new DanmoShoppingCart();
            danmoShoppingCart.setId(shoppingCartModificationDto.getId());
            danmoShoppingCart.setUserId(userId);
            danmoShoppingCart.setQuantity(shoppingCartModificationDto.getTotalQuantity());
            danmoShoppingCart.setChecked(shoppingCartModificationDto.getChecked());
            danmoShoppingCartMapper.updateDanmoShoppingCart(danmoShoppingCart);
        }
        return Result.success(1, "修改成功");
    }

    /**
     * 批量删除购物车
     *
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public Result deleteDanmoShoppingCartByIds(Long[] ids) {
        danmoShoppingCartMapper.deleteDanmoShoppingCartByIds(ids);
        return Result.success(1, "删除成功");
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deleteDanmoShoppingCartById(Long id) {
        return danmoShoppingCartMapper.deleteDanmoShoppingCartById(id);
    }

    /**
     * 查看购物车列表
     *
     * @param loginUser 用户信息
     * @return 结果
     */
    @Override
    public ShoppingCartDto selectDanmoShoppingCartList(LoginUser loginUser) {
        ShoppingCartDto shoppingCartDto = new ShoppingCartDto();
        shoppingCartDto.setTotalPrice(BigDecimal.valueOf(0));
        shoppingCartDto.setTotalQuantity((long) 0);


        // 获取该用户的购物车项
        List<DanmoShoppingCart> cartItems = danmoShoppingCartMapper.findByUserId(loginUser.getUserid());

        // 用于按旗舰店分组的 Map
        Map<String, CartItemDto> flagshipMap = new HashMap<>();

        for (DanmoShoppingCart cartItem : cartItems) {
            DanmoShoppingProducts product = danmoShoppingProductsMapper.findById(cartItem.getProductId());
            DanmoShoppingSpecification specification = danmoShoppingSpecificationMapper.findById(cartItem.getShoppingSkuId());

            if (product != null && specification != null) {

                // 旗舰店名称
                String flagshipName = product.getFlahshipName();

                // 创建 CartItemDto 如果旗舰店不存在
                CartItemDto dto = flagshipMap.get(flagshipName);
                if (dto == null) {
                    dto = new CartItemDto();
                    dto.setUserId(loginUser.getUserid());
                    dto.setFlagshipName(flagshipName);
                    dto.setLogoUrl(product.getLogoUrl());
                    dto.setShopId(product.getFlahship());
                    dto.setDanmoShoppingCartLists(new ArrayList<>());
                    flagshipMap.put(flagshipName, dto);
                }

                // 创建购物车商品列表项
                DanmoShoppingCartList cartListItem = new DanmoShoppingCartList();
                cartListItem.setId(cartItem.getId());
                cartListItem.setProductId(product.getId());
                cartListItem.setSpecName(specification.getName());
                cartListItem.setQuantity(cartItem.getQuantity());
                cartListItem.setPrice(cartItem.getPrice());
                cartListItem.setPicture(product.getPicture());
                cartListItem.setProductName(product.getName());
                cartListItem.setPoxExpress(product.getPosExpress());
                cartListItem.setFreight(product.getFreight());
                cartListItem.setChecked(true);
                cartListItem.setShoppingSkuId(cartItem.getShoppingSkuId());
                cartListItem.setChecked(cartItem.getChecked());
                if (!cartItem.getChecked()) {
                    dto.setChecked(false);
                }else {
                    shoppingCartDto.setTotalPrice(shoppingCartDto.getTotalPrice().add(cartListItem.getPrice().multiply(BigDecimal.valueOf(cartItem.getQuantity()))));
                    shoppingCartDto.setTotalQuantity(shoppingCartDto.getTotalQuantity() + cartItem.getQuantity());
                }

                // 将商品项加入到该旗舰店的商品列表
                dto.getDanmoShoppingCartLists().add(cartListItem);
            }
        }
        shoppingCartDto.setDanmoShoppingCartLists(new ArrayList<>(flagshipMap.values()));
        return shoppingCartDto;
    }

    /**
     * 购物车结算
     *
     * @param ids 结算商品id
     * @return 结果
     */
    @Override
    @Transactional // 添加事务管理
    public Result<String> settlementDanmoShoppingCartByIds(Long[] ids) {
        // 查询出当前用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 支付总额
        BigDecimal total = BigDecimal.ZERO; // 使用 BigDecimal 来存储总金额

        // 查询需要结算的所有商品
        for (int i = 0; i < ids.length; i++) {
            // 查询当前购物车对象
            DanmoShoppingCart danmoShoppingCart = danmoShoppingCartMapper.selectDanmoShoppingCartByIds(ids[i]);
            if (!danmoShoppingCart.getUserId().equals(loginUser.getUserid())) {
                throw new RuntimeException("支付错误，请重试");
            }
            // 查询商品库存数量
            Long productId = danmoShoppingCart.getProductId();
            Long shoppingSkuId = danmoShoppingCart.getShoppingSkuId();
            DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsAndSkuById(productId, shoppingSkuId);
            if (danmoShoppingProducts == null) {
                throw new RuntimeException("商品不存在");
            }
            if (danmoShoppingProducts.getSkuStock() == null || danmoShoppingProducts.getSkuStock() == 0) {
                throw new RuntimeException("商品已售空");
            }
            if (danmoShoppingCart.getQuantity() == null || danmoShoppingCart.getQuantity() == 0) {
                throw new RuntimeException("购物车商品数量不能为空");
            }
            Long stock = danmoShoppingProducts.getSkuStock() - danmoShoppingCart.getQuantity();
            if (stock < 0) {
                throw new RuntimeException("支付错误，请重试");
            }
            // 计算总价
            BigDecimal quantity = BigDecimal.valueOf(danmoShoppingCart.getQuantity());
            BigDecimal itemTotal = danmoShoppingCart.getPrice().multiply(quantity);
            total = total.add(itemTotal);

            // 商品销量加1
            // 修改商品库存数量
            Long sales = danmoShoppingProducts.getSales() + Long.valueOf(danmoShoppingCart.getQuantity());
            danmoShoppingProductsMapper.updateDanmoShoppingProduct(stock, danmoShoppingCart.getProductId(), sales);
            // 将付款成功的在购物车中删除
            danmoShoppingCartMapper.deleteDanmoShoppingCartById(danmoShoppingCart.getId());
        }
        // 返回结果
        return Result.success("购买成功");
    }


    @Override
    public Result insertDanmoMarketCollect(Long[] productsIds) {
        //前端没带请求头稍等一下   看下数据库有没有数据
        //SecurityUtils securityUtils = new SecurityUtils();
        Long userId = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return Result.notLoggedIn("请登录");
        }
        userId = loginUser.getUserid();
        DanmoShoppingProductsCollection danmoShoppingProductsCollection = new DanmoShoppingProductsCollection();
        danmoShoppingProductsCollection.setUserId(userId);
        danmoShoppingProductsCollection.setCreateBy(String.valueOf(loginUser.getUserid()));
        danmoShoppingProductsCollection.setCreateTime(DateUtils.getNowDate());
        danmoShoppingProductsCollection.setUpdateBy(String.valueOf(loginUser.getUserid()));
        danmoShoppingProductsCollection.setUpdateTime(DateUtils.getNowDate());
        for (Long productsId : productsIds) {
//            1.先去查询购物车中的商品id
            DanmoShoppingProductsCollection danmoShoppingProductsCollection1 = danmoShoppingProductsCollectionMapper.selectDanmoShoppingProductsCollectionByProductsId(productsId);
            if (danmoShoppingProductsCollection1 == null) {
                //            2.将id插入到商品收藏对象中
                danmoShoppingProductsCollection.setGoodsId(productsId);
                danmoShoppingProductsCollectionMapper.insertDanmoShoppingProductsCollection(danmoShoppingProductsCollection);
            }
        }
        return Result.success(1, "收藏成功");
    }

    @Override
    public Result selectDanmoShoppingCart(ShoppingCartDto shoppingCartDto) {
        for (CartItemDto danmoShoppingCartList : shoppingCartDto.getDanmoShoppingCartLists()) {
            danmoShoppingCartList.setChecked(true);
            for (DanmoShoppingCartList shoppingCartList : danmoShoppingCartList.getDanmoShoppingCartLists()) {
                DanmoShoppingCart danmoShoppingCart = new DanmoShoppingCart();
                danmoShoppingCart.setId(shoppingCartList.getId());
                danmoShoppingCart.setProductId(shoppingCartList.getProductId());
                danmoShoppingCart.setShoppingSkuId(shoppingCartList.getShoppingSkuId());
                danmoShoppingCart.setQuantity(shoppingCartList.getQuantity());
                danmoShoppingCart.setChecked(true);
                if (shoppingCartList.getChecked()) {
                    DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsById(shoppingCartList.getProductId());
                    if (danmoShoppingProducts.getStock() < shoppingCartList.getQuantity()) {
                        return Result.error(1, "库存不足");
                    }
                    danmoShoppingCart.setPrice(danmoShoppingProducts.getPrice());
                    danmoShoppingCart.setChecked(true);
                    danmoShoppingCartMapper.updateDanmoShoppingCart(danmoShoppingCart);

                    // 修复代码部分
                    BigDecimal quantity = BigDecimal.valueOf(shoppingCartList.getQuantity());
                    BigDecimal totalPrice = shoppingCartDto.getTotalPrice();
                    BigDecimal itemTotalPrice = shoppingCartList.getPrice().multiply(quantity);
                    shoppingCartDto.setTotalPrice(totalPrice.add(itemTotalPrice));
                    shoppingCartDto.setTotalQuantity(shoppingCartDto.getTotalQuantity() + danmoShoppingCart.getQuantity());
                } else {
                    DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsById(shoppingCartList.getProductId());
                    danmoShoppingCart.setPrice(danmoShoppingProducts.getPrice());
                    danmoShoppingCart.setChecked(false);
                    danmoShoppingCartMapper.updateDanmoShoppingCart(danmoShoppingCart);
                    danmoShoppingCartList.setChecked(false);
                }
            }
        }
        return Result.success(shoppingCartDto);
    }

    @Override
    public IPage<FindCartVO> findCart(FindCartDTO findCartDTO) {
        IPage<FindCartVO> cart = danmoShoppingCartMapper.findCart(new Page<>(findCartDTO.getPageNum(), findCartDTO.getPageSize()), findCartDTO.getUserId());
        return cart;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteCart(Long id) {
        dmShoppingCartMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteCartList(List<Long> ids) {
        dmShoppingCartMapper.deleteBatchIds(ids);
    }
}
